package com.haohan.cloud.scm.common.tools.util;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.haohan.cloud.scm.common.tools.constant.AliyunConstant;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.experimental.UtilityClass;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author dy
 * @date 2019/10/30
 */
@UtilityClass
public class AliyunOssUtils implements AliyunConstant {

    /**
     * 上传文件
     *
     * @param file
     * @param objectName 文件对象名称 文件链接名
     * @return
     */
    public R<String> uploadFile(MultipartFile file, String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 上传文件流。
        try {
            ossClient.putObject(BUCKET_NAME, objectName, file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed(e.getMessage());
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        return RUtil.success(FILE_BUCKET_HTTP.concat(FILE_SEPARATOR).concat(objectName));
    }

    /**
     * 设置文件路径
     *
     * @param sn
     * @param type
     * @return
     */
    public String fetchFilePath(String sn, String type) {
        //日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String dateStr = formatter.format(LocalDate.now());
        //路径拼接
        return MERCHANT_FILE_FOLDER +
                FILE_SEPARATOR +
                sn +
                FILE_SEPARATOR +
                type +
                FILE_SEPARATOR +
                dateStr +
                FILE_SEPARATOR;
    }

    /**
     * 时间戳 + 4位随机字符 + 后缀
     *
     * @param suffix 文件名后缀 .jpg
     * @return
     */
    public String fetchFileName(String suffix) {
        String time = String.valueOf(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
        String s = RandomUtil.randomString("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4);
        return time + s + suffix;
    }

}



